package com.gsn.login;

import java.io.File;

import org.json.JSONObject;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.ClickListener;
import com.badlogic.gdx.scenes.scene2d.ui.GsnImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle;
import com.gsn.dataCommon.UserData;
import com.gsn.desktop.engine.ActorUtility;
import com.gsn.engine.gdx.GsnParticleActor;
import com.gsn.engine.myplay.GsnLayer;
import com.gsn.engine.utility.UtilityGettor;
import com.gsn.engine.utility.IUtility.IPictureDownloadListener;
import com.gsn.name.NameEdit;
import com.gsn.name.SessionkeyZingMe;
import com.gsn.poker.asset.FontTexture;
import com.gsn.poker.asset.PokerSound;
import com.gsn.poker.asset.PortalTexture;
import com.gsn.poker.game.MyPoker;

public class LoginLayer extends GsnLayer implements ClickListener {

	PortalTexture portalTexture;
	FontTexture fontTexture;

	GsnImageButton helpButton;
	GsnImageButton registerButton;
	GsnImageButton inviteButton;
	GsnImageButton loginButton;
	GsnImageButton checkButton;

	// public TextField labelPassField;
	// public TextField labelNameField;

	public static final String NAME = "name";
	public static final String PASSWORD = "password";
	public static final String SAVE_PASS = "savePass";
	public static final String SESSION_KEY = "sessionKey";

	public static final String SOUND = "sound";
	public static final String MUSIC = "music";
	public static final String VIBRATE = "vibrate";

	private static final String tag = "Login Layer";

	public LoginLayer(float width, float height) {
		super(width, height);
		portalTexture = PortalTexture.inst();
		fontTexture = FontTexture.inst();
		init();

	}

	public void init() {
		Image bg = new Image(portalTexture.bgPortal);
		bg.width = width;
		bg.height = height;
		addActor(bg);

		Image girl = new Image(portalTexture.iconGirl);
		portalTexture.scaleActor(girl);
		addActor(girl);

		helpButton = new GsnImageButton(portalTexture.helpButton, portalTexture.helpButtonPress);
		helpButton.setScale(MyPoker.game.scale);
		// portalTexture.scaleActor();

		addActor(helpButton);
		helpButton.setClickListener(this);
		helpButton.x = width - helpButton.getRealWidth();
		// ActorUtility.setRatio(helpButton, 1.0f, 0, width, 0);
		// ActorUtility.setCenter(actor, x, y)

		registerButton = new GsnImageButton(portalTexture.registerButton, portalTexture.registerButtonPress);
		portalTexture.scaleActor(registerButton);
		// registerButton.setScale(MyPoker.game.scale);

		addActor(registerButton);
		// registerButton.setScale(MyPoker.game.scale);
		registerButton.setScale(MyPoker.game.scale);
		registerButton.setClickListener(this);
		registerButton.x = helpButton.x - registerButton.getRealWidth();
		// ActorUtility.setRatio(registerButton, 1, 0, helpButton.x, 0);

		inviteButton = new GsnImageButton(portalTexture.inviteButton, portalTexture.inviteButtonPress);
		portalTexture.scaleActor(inviteButton);
		addActor(inviteButton);
		// inviteButton.setScale(MyPoker.game.scale);
		inviteButton.setClickListener(this);
		inviteButton.x = registerButton.x - inviteButton.getRealWidth();

		Image title = new Image(portalTexture.title);
		portalTexture.scaleActor(title);
		title.x = width - title.width - 0.05f * width;
		title.y = inviteButton.getRealHeight() * 1.3f;
		addActor(title);

		Image logo = new Image(portalTexture.logo);
		portalTexture.scaleActor(logo);
		logo.x = title.x - logo.width;
		logo.y = title.y;
		addActor(logo);

		loginButton = new GsnImageButton(portalTexture.loginButton, portalTexture.loginButtonPress);
		portalTexture.scaleActor(loginButton);
		addActor(loginButton);
		// loginButton.setScale(MyPoker.game.scale);
		loginButton.setClickListener(this);
		loginButton.x = width * 0.55f;
		loginButton.y = logo.y + 1.0f * logo.height;

		checkButton = new GsnImageButton(portalTexture.checkButton, portalTexture.checkButton, portalTexture.checkButtonPress);
		portalTexture.scaleActor(checkButton);
		addActor(checkButton);
		// checkButton.setScale(MyPoker.game.scale);
		checkButton.setClickListener(this);
		checkButton.x = width / 2;
		checkButton.y = loginButton.y + loginButton.getRealHeight() * 1.2f;

		Label save = new Label("Lưu tài khoản", new Label.LabelStyle(FontTexture.inst().fontMedium, new Color(1, 1, 1, 1)));
		addActor(save);
		save.x = checkButton.x + checkButton.getRealWidth() * 1.50f;
		save.y = checkButton.y;

		Image editPass = new Image(portalTexture.textBoxGrey);
		portalTexture.scaleActor(editPass);

		// editPass.scaleX = editPass.scaleY
		editPass.x = width / 2;
		editPass.y = checkButton.y + checkButton.getRealHeight() * 1.2f;
		addActor(editPass);

		// labelPassField = new TextField(PortalTexture.inst().skin);
		// addActor(labelPassField);
		// labelPassField.x = editPass.x;
		// labelPassField.y = editPass.y;

		Label labelPass = new Label("Mật khẩu", new Label.LabelStyle(FontTexture.inst().fontMedium, new Color(1, 1, 1, 1)));
		addActor(labelPass);
		labelPass.x = width / 2;
		labelPass.y = editPass.y + editPass.height * 1.2f;

		Image editAcount = new Image(portalTexture.textBoxGrey);
		portalTexture.scaleActor(editAcount);
		// editAcount.width = width * 0.43f;
		editAcount.x = width / 2;
		editAcount.y = labelPass.y + editAcount.height * 1.2f;
		addActor(editAcount);

		// labelNameField = new TextField(PortalTexture.inst().skin);
		// addActor(labelNameField);
		// labelNameField.x = editAcount.x;
		// labelNameField.y = editAcount.y;

		Label labelAcount = new Label("Tài khoản", new Label.LabelStyle(FontTexture.inst().fontMedium, new Color(1, 1, 1, 1)));
		addActor(labelAcount);
		labelAcount.x = width / 2;
		labelAcount.y = editAcount.y + editAcount.height * 1.2f;

		// if (UtilityGettor.onMobile) {
		// UtilityGettor.inst().load();
		// labelNameField.visible = false;
		// labelPassField.visible = false;
		// camera.position.set(width / 4, height / 4, 0);
		UtilityGettor.inst().makeTextFieldWithScreenCoordinate(this, PortalTexture.inst().skin.getStyle(TextFieldStyle.class), NameEdit.NAME_USER, UserData.name, editAcount.width, editAcount.height, height - editAcount.y - editAcount.height, editAcount.x);
		UtilityGettor.inst().makeTextFieldWithScreenCoordinate(this, PortalTexture.inst().skin.getStyle(TextFieldStyle.class), NameEdit.PASS_USER, UserData.passWord, editPass.width, editPass.height, height - editPass.y - editAcount.height, editPass.x);
		// }
		checkButton.setChecked(UserData.save);

		if (UserData.sessionKey.equals("")) {

		}

		loginButton.setClickListener(this);
	}

	@Override
	public void click(Actor actor, float x, float y) {
		// TODO Auto-generated method stub
		GsnParticleActor par = new GsnParticleActor(PortalTexture.inst().clickEff);
		Vector2 v = ActorUtility.getCoordinate(actor, x, y, this.root);

		par.setPostition(v.x, v.y);

		par.act(100000);
		addActor(par);
		par.start();

		String name;
		String pass;
		PokerSound.playClick();
		if (actor == inviteButton) {
			UtilityGettor.inst().inviteFriend();
		} else if (actor == registerButton) {
			UtilityGettor.inst().register();
		} else if (actor == loginButton) {
			// if (UtilityGettor.onMobile)
			// {
			name = UtilityGettor.inst().getString(NameEdit.NAME_USER);
			pass = UtilityGettor.inst().getString(NameEdit.PASS_USER);

			// } else {
			// name = labelNameField.getText();
			// pass = labelPassField.getText();
			// }

			Gdx.app.log(tag, "name  : !" + name + "!");
			Gdx.app.log(tag, "pass  : !" + pass + "!");
			name = name.trim();
			pass = pass.trim();
			// name = "simo06";
			// pass = "handoi";
			String sess = null;
			JSONObject json;

			if (name.equals("")) {
				UtilityGettor.inst().toast("Vui lòng nhập tên tài khoản", true);
				return;
			} else if (pass.equals("")) {
				UtilityGettor.inst().toast("Vui lòng nhập mật khẩu đăng nhập", true);
				return;
			}

			name = getStandartString(name);
			pass = getStandartString(pass);

			UtilityGettor.inst().showProgressDialog("Đang kết nối", "Kết nối...");

			if (name.equals(UserData.name) && pass.equals(UserData.passWord) && UserData.sessionKey != null && !UserData.sessionKey.equals("")) {
				try {
					json = SessionkeyZingMe.getInfo();

					if (json != null)
						UserData.avatar = json.getString("headurl");
					else {
						UtilityGettor.inst().hideProgressDialog();
						UtilityGettor.inst().toast("Kiểm tra lại kết nối mạng", false);
						return;
					}
					UserData.name = name;
					UserData.passWord = pass;

					if (UserData.save) {

						save();
					} else {
						remove();
					}
					UtilityGettor.inst().hideProgressDialog();
					MyPoker.game.setChooseGameScreen();

				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					UtilityGettor.inst().hideProgressDialog();

					UtilityGettor.inst().toast("Kiểm tra lại kết nối mạng", false);

				}
			} else {
				try {
					sess = SessionkeyZingMe.getSessionkeyUser(name, pass, true);

					if (sess != null) {

						UserData.name = name;
						UserData.passWord = pass;
						UserData.sessionKey = sess;
						if (UserData.save) {

							save();
						} else {
							remove();
						}
						try {
							json = SessionkeyZingMe.getInfo();
							if (json != null)
								UserData.avatar = json.getString("headurl");
							UtilityGettor.inst().hideProgressDialog();
							MyPoker.game.setChooseGameScreen();

						} catch (Exception e) {
							// TODO: handle exception
							UtilityGettor.inst().hideProgressDialog();

							UtilityGettor.inst().toast("Kiểm tra lại kết nối mạng", false);

						}

					} else {
						MyPoker.game.loginScreen.showDialogString("Tài khoản đăng nhập không đúng, vui lòng kiểm tra và thử lại?");
						UtilityGettor.inst().hideProgressDialog();

					}
				} catch (Exception e) {
					// TODO: handle exception
					// truong hop ko co mang
					UtilityGettor.inst().hideProgressDialog();
					Gdx.app.log(tag, "session : " + sess);
					UtilityGettor.inst().toast("Kiểm tra lại kết nối mạng", false);
					return;
				}

			}

		} else if (actor == checkButton) {
			UserData.save = !UserData.save;
		} else if (actor == helpButton) {
			MyPoker.game.loginScreen.showHelpDialog();
			UtilityGettor.inst().hideTextField(NameEdit.NAME_USER);
			UtilityGettor.inst().hideTextField(NameEdit.PASS_USER);
		}
	}

	public void remove() {
		Preferences shareData = Gdx.app.getPreferences("portal");

		shareData.remove(SAVE_PASS);
		shareData.remove(NAME);
		shareData.remove(PASSWORD);
		shareData.remove(SESSION_KEY);
		shareData.flush();

	}

	public void saveSetting() {
		Preferences shareData = Gdx.app.getPreferences("portal");
		shareData.putBoolean(SOUND, UserData.sound);
		shareData.putBoolean(MUSIC, UserData.music);
		shareData.putBoolean(VIBRATE, UserData.vibrate);

		shareData.flush();
	}

	public void save() {

		Preferences shareData = Gdx.app.getPreferences("portal");
		shareData.putString(NAME, UserData.name);
		shareData.putString(PASSWORD, UserData.passWord);
		shareData.putBoolean(SAVE_PASS, UserData.save);

		shareData.putString(SESSION_KEY, UserData.sessionKey);

		shareData.flush();
	}

	@Override
	public boolean keyDown(int keycode) {
		// TODO Auto-generated method stub
		switch (keycode) {
		case Keys.BACK:

			break;

		default:
			break;
		}
		return super.keyDown(keycode);
	}

	public String getStandartString(String s) {
		String result = "";

		int i;
		for (i = 0; i < s.length(); i++) {
			if (s.charAt(i) != ' ') {
				result = result + s.charAt(i);
			}
		}
		return result;

	}
}
